package cn.tedu.toa.management.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
public class UploadUtils {

    public String uploadImage(MultipartFile imageFile) throws IOException {
        File resourcePath = new File(
                System.getProperty("user.dir")+"/src/main/resources/static/front/image");
        //确定要上传的路径
        String path= DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        //确定要保存的文件名
        File folder= new File(resourcePath,path);
        folder.mkdirs();
        String name= UUID.randomUUID().toString();
        //确定扩展名
        String original=imageFile.getOriginalFilename();
        String ext=original.substring(original.lastIndexOf("."));
        String fullName=name+ext;
        log.debug("即将上传的文件名为:{}",fullName);
        File file= new File(folder,fullName);
        log.debug("即将上传{}",resourcePath);

        //执行保存文件到服务器
        imageFile.transferTo(file);
        log.debug("上传");

        //拼接一个可以访问静态资源的URL
        String url="/images/"+path+"/"+fullName;
        log.debug("即将上传的文件:{}",url);

        //返回上传的信息
        return url;
    }
}
